export function Connect(options) {
    // 这个连接指的是，后端将用户信息与ws是否完成对应。
    this.isConnected = false;
    this.url = options.url;
    this.protocols = options.protocols;
    if (options.param) {
        this.url += '?';
        Object.keys(options.param).forEach((key, index) => {
            this.url += `${key}=${options.param[key]}`;
            if (index !== Object.keys(options.param).length - 1) {
                this.url += '&';
            }
        });
    }
    
    this.ws = null;
}

Connect.prototype.connect = function() {
    if (this.isConnected) {
        return Promise.reject('已经连接');
    }
    const { url, protocols } = this;
    this.ws = new WebSocket(url, protocols);
    return new Promise((resolve) => {
        let ev = () => {
            this.ws.removeEventListener('open', ev);   
            this.isConnected = true;
            resolve();
        }
        this.ws.addEventListener('open', ev);
    })
}

Connect.prototype.close = function () {
    this.ws.close();
};

Connect.prototype.send = function (msg) {
    this.ws.send(msg);
};
